package com.wyj.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO:
 *
 * @author wuyijie
 * @date 2021/12/25 11:06 下午
 */
public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {
    private static final List<Channel> CHANNEL_LIST = new ArrayList<>();

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNEL_LIST.add(channel);
        System.out.println("【服务端接收到" + channel.remoteAddress().toString().substring(1) + " 的连接】");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Channel channel = channelHandlerContext.channel();
        for (Channel channel1 : CHANNEL_LIST) {
            if (channel != channel1) {
                channel1.writeAndFlush("客户端" + channel1.remoteAddress().toString().substring(1) + "说：" + s + "");
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        CHANNEL_LIST.remove(channel);
        System.out.println("【服务端接断开：" + channel.remoteAddress().toString().substring(1) + " 的连接】");

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        CHANNEL_LIST.remove(channel);
        System.out.println("【客户端" + channel.remoteAddress().toString().substring(1) + " 发生异常，断开连接】");
    }


}
